<script lang="ts" setup>
import type { VxeGridInstance, VxeGridProps } from "vxe-table"
import { computed, onMounted, reactive, ref, useTemplateRef } from "vue"
import { useRouter } from "vue-router"
import { usePositionStudentStore } from "@/pinia/stores/position-student"
import { usePositionTeacherStore } from "@/pinia/stores/position-teacher"
import { useUserStore } from "@/pinia/stores/user"
import PositionDetailModal from "./components/PositionDetailModal.vue"
import PositionEditModal from "./components/PositionEditModal.vue"

defineOptions({
  // 命名当前组件
  name: "PositionTeacherManagement"
})

const positionTeacherStore = usePositionTeacherStore()
const positionStudentStore = usePositionStudentStore()
const userStore = useUserStore()
const router = useRouter()

// #region vxe-grid
interface RowMeta {
  positionId: number
  positionName: string
  salary: string
  companyName: string
  workCity: string
  positionType: string
  workType: string
  period: string
  recruitNum: number
  publishUserName: string
  publishUserId: number
  applyCount: number
  passCount: number
  admissionCount: number
  isRecommend: boolean
  deadline: string
  status: string
  /** vxe-table 自动添加上去的属性 */
  _VXE_ID?: string
}

const xGridDom = useTemplateRef<VxeGridInstance>("xGridDom")

// 使用computed属性来响应options变化
const workTypeOptions = computed(() => positionStudentStore.workTypeOptions)
const workCityOptions = computed(() => positionStudentStore.workCityOptions)
const periodOptions = computed(() => positionStudentStore.periodOptions)
const salaryOptions = computed(() => positionStudentStore.salaryOptions)
const positionTypeOptions = computed(() => positionStudentStore.positionTypeOptions)

function createFormConfigItems() {
  return [
    {
      field: "workType",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "工作类型",
          clearable: true,
          options: workTypeOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "workCity",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "工作城市",
          clearable: true,
          options: workCityOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "period",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "实习周期",
          clearable: true,
          options: periodOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "salary",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "薪资范围",
          clearable: true,
          options: salaryOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "positionType",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "岗位类型",
          clearable: true,
          options: positionTypeOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "keyword",
      itemRender: {
        name: "VxeInput",
        props: {
          placeholder: "职位名称/公司名称",
          clearable: true
        },
        events: {
          keyup: (event: KeyboardEvent) => {
            if (event.key === "Enter") {
              xGridDom.value?.commitProxy("query")
            }
          }
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      itemRender: {
        name: "VxeButtonGroup",
        options: [
          {
            type: "submit",
            content: "查询",
            status: "primary"
          },
          {
            type: "reset",
            content: "重置",
            events: {
              click: () => {
                if (xGridDom.value) {
                  // 重置pinia中的查询参数
                  positionTeacherStore.resetQueryParams()
                  // 重置表格筛选条件
                  xGridDom.value.clearFilter()
                  // 清空表格数据
                  xGridDom.value.reloadData([])
                  // 重新查询
                  xGridDom.value.commitProxy("query")
                }
              }
            } as { [key: string]: (...args: any[]) => any }
          }
        ]
      }
    }
  ]
}

const xGridOpt: VxeGridProps = reactive({
  loading: false,
  autoResize: true,
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: createFormConfigItems()
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: true,
    columns: true,
    slots: {
      buttons: "toolbar-btns"
    }
  },
  /** 列配置 */
  columns: [
    {
      type: "seq",
      title: "编号",
      width: 50,
      align: "center"
    },
    {
      field: "positionName",
      title: "职位名称",
      minWidth: 100
    },
    {
      field: "companyName",
      title: "公司名称",
      minWidth: 120
    },
    {
      field: "salary",
      title: "薪资",
      minWidth: 50,
      visible: false
    },
    {
      field: "positionType",
      title: "岗位类型",
      visible: false,
      minWidth: 50
    },
    {
      field: "workCity",
      title: "工作城市"
    },
    {
      field: "workType",
      title: "工作类型"
    },
    {
      field: "period",
      title: "实习周期"
    },
    {
      field: "recruitNum",
      title: "招聘人数"
    },
    {
      field: "publishUserName",
      title: "发布人",
      visible: false
    },
    {
      field: "applyCount",
      title: "申请人数"
    },
    {
      field: "passCount",
      title: "通过人数"
    },
    {
      field: "admissionCount",
      title: "录用人数"
    },
    {
      field: "isRecommend",
      title: "是否推荐",
      visible: false
    },
    {
      field: "deadline",
      title: "截止时间",
      minWidth: 50,
      visible: false
    },
    {
      field: "status",
      title: "状态"
    },
    {
      title: "操作",
      width: "250px",
      fixed: "right",
      showOverflow: false,
      slots: {
        default: "row-operate"
      }
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({ page, form }) => {
        xGridOpt.loading = true
        return new Promise((resolve) => {
          // 更新查询参数
          positionTeacherStore.updateQueryParams({
            keyword: form.keyword || "",
            workType: form.workType,
            workCity: form.workCity,
            period: form.period,
            salary: form.salary,
            positionType: form.positionType,
            page: page.currentPage,
            size: page.pageSize
          })

          // 加载数据并处理结果
          const callback = () => {
            xGridOpt.loading = false
            resolve({
              total: positionTeacherStore.total,
              result: positionTeacherStore.list
            })
          }

          positionTeacherStore.fetchPositionList().then(callback).catch(callback)
        })
      }
    }
  }
})
// #endregion

// #region 增删改查
const crudStore = reactive({
  /** 查看详情 */
  onViewDetail: (row: RowMeta) => {
    showDetailModal.value = true
    currentPositionId.value = row.positionId
  },
  /** 新增职位 */
  onAddPosition: () => {
    showEditModal.value = true
    editPositionId.value = 0
  },
  /** 编辑职位 */
  onEditPosition: (row: RowMeta) => {
    showEditModal.value = true
    editPositionId.value = row.positionId
  },
  /** 前去审核 */
  onReviewApplications: (row: RowMeta) => {
    router.push({
      name: "PositionTeacherPaneReview",
      query: { positionId: row.positionId }
    })
  },
  /** 更多自定义方法 */
  moreFn: () => {}
})

// 详情模态框控制
const showDetailModal = ref(false)
const currentPositionId = ref(0)

// 编辑模态框控制
const showEditModal = ref(false)
const editPositionId = ref(0)

// 关闭详情模态框回调
function handleDetailModalClose() {
  currentPositionId.value = 0
}

// 关闭编辑模态框回调
function handleEditModalClose() {
  editPositionId.value = 0
}

// 编辑模态框成功回调
function handleEditModalSuccess() {
  // 刷新列表数据
  xGridDom.value?.commitProxy("query")
}
// #endregion

// 初始化
onMounted(async () => {
  // 先获取选项数据
  await positionStudentStore.fetchOptions()
  // 再加载列表数据
  xGridDom.value?.commitProxy("query")
})
</script>

<template>
  <div class="app-container">
    <!-- 表格 -->
    <vxe-grid ref="xGridDom" v-bind="xGridOpt">
      <!-- 左侧按钮列表 -->
      <template #toolbar-btns>
        <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onAddPosition">
          新增职位
        </vxe-button>
      </template>
      <!-- 操作列 -->
      <template #row-operate="{ row }">
        <el-button link type="primary" @click="crudStore.onViewDetail(row)">
          查看详情
        </el-button>
        <el-button link type="primary" @click="crudStore.onEditPosition(row)">
          编辑
        </el-button>
        <el-button
          link
          type="primary"
          @click="crudStore.onReviewApplications(row)"
          :disabled="row.publishUserId !== userStore.userInfo?.userId"
        >
          审核
        </el-button>
      </template>
    </vxe-grid>

    <!-- 职位详情模态框 -->
    <PositionDetailModal
      v-model="showDetailModal"
      :position-id="currentPositionId > 0 ? currentPositionId : undefined"
      @close="handleDetailModalClose"
    />

    <!-- 职位编辑模态框 -->
    <PositionEditModal
      v-model="showEditModal"
      :position-id="editPositionId > 0 ? editPositionId : undefined"
      @close="handleEditModalClose"
      @success="handleEditModalSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

// 表格样式优化
:deep(.vxe-table) {
  .vxe-body--row {
    &:hover {
      background-color: #f5f7fa;
    }
  }

  .vxe-cell {
    line-height: 32px;
  }

  .el-tag {
    margin: 0;
    height: 24px;
    line-height: 22px;
  }
}
</style>
